#include <errno.h>
#include <sys/socket.h>
#include "read_buffer.h"
#include "http_server.h"

int read_buffer (http_connection_t *http_connection)
{
	buffer_t *buffer = &http_connection->buffer;
	ssize_t bytes;

	bytes = recv (http_connection->sd, buffer->data + buffer->used, buffer->size - buffer->used, 0);
	if (bytes < 0) {
		if (errno == EAGAIN) {
			return 0;
		} else if (errno == EINTR) {
			/* The call was interrupted by a signal before any data was read. */
			/* Add ourself to the list of interrupted HTTP connections. */
			http_server.interrupted_http_connections[http_server.number_interrupted_http_connections++] = http_connection;

			return 0;
		} else {
			return -1;
		}
	} else if (bytes == 0) {
		/* The peer has performed an orderly shutdown. */
		return -1;
	}

	http_connection->last_read_write = http_server.current_time;

	http_connection->received += bytes;

	buffer->used += bytes;

	return bytes;
}
